﻿//Author:Christian TQ
//******************************************************************************************
//SEARCH DOC LIB
//******************************************************************************************
var newUrl = "";
$(document).ready(function () {
    // blur
    $('#DocLibSearchBox, textarea').focus(function () {
        value = $(this).val();
        $(this).attr("value", "");
    });
    $('#DocLibSearchBox, textarea').blur(function () {
        if ($(this).val() == "")
            $(this).val(value);
    });

    //get url
    var docLibUrl = new Array();
    docLibUrl = window.location.href.split('/');
    for (var i = 0; i < (docLibUrl.length - 1); i++)
        newUrl += docLibUrl[i] + "/";

    $('#DocLibSearchBox').keyup(function (event) {
        var previousSelected = quickSearchSelectedDivIndex;

        switch (event.keyCode) {
            case 13:    //enter
                var selectedDiv = $("#quickSearchResults>div:eq(" + quickSearchSelectedDivIndex + ") a");
                if (selectedDiv.length == 1)
                    window.location = selectedDiv.attr("href");
                break;
            case 38:    //keyup
                quickSearchSelectedDivIndex--;
                break;
            case 40:    //keydown
                quickSearchSelectedDivIndex++;
                break;
        }


        // check bounds
        if (quickSearchSelectedDivIndex != previousSelected) {
            if (quickSearchSelectedDivIndex < 0)
                quickSearchSelectedDivIndex = 0;
            if (quickSearchSelectedDivIndex >= $("#quickSearchResults>div").length - 1)
                quickSearchSelectedDivIndex = $("#quickSearchResults>div").length - 2;
        }


        //  if the query is different from the previous one, search again
        if ($('#DocLibSearchBox').data("query") != $('#DocLibSearchBox').val()) {
            if (quickSearchTimer != null) // cancel the delayed event
                clearTimeout(quickSearchTimer);
            quickSearchTimer = setTimeout(function () { // delay the searching
                $("#quickSearchResults").fadeOut(200, initSearch);
            }, config.delay);
        }
    });
});


function showResultsDiv(text) {

    var div = $("#quickSearchResults");
    var prevTable = $("#DocLibSearchBox");
    var divCss = {
        "left": prevTable.offset().left - (prevTable.width() - 67),
        "padding": 2,
        "position": "absolute",
        "top": prevTable.offset().top - (prevTable.height() + 103),
        "border": "1px solid #7f9db9",
        "width": prevTable.width(),
        "background": "white",
        "max-width": prevTable.width()
    };


    div.css(divCss).append(text).slideDown(config.resultsAnimation);
}

function initSearch() {

    // first store query in data
    $('#DocLibSearchBox').data("query", $('#DocLibSearchBox').val());

    // clear the results
    $("#quickSearchResults").empty();

    // start the search
    var query = $("#DocLibSearchBox").val();
    if (query.length >= config.minCharacters) {
        showResultsDiv("<center>Searching document...<img alt='loading' src='_layouts/images/loading16.gif' border='0'/></center>"); // display status
        searchListItem(query);
    }
}


function searchListItem(keyword) {
    try {
        var context = SP.ClientContext.get_current();
        var web = context.get_web();
        var list = web.get_lists().getByTitle(config.listTitle);
        var query = '<View Scope=\'RecursiveAll\'><Query><Where><Contains><FieldRef Name=\'' + config.fieldName + '\'/><Value Type=\'Text\'>' + keyword + '</Value></Contains></Where><OrderBy><FieldRef Name=\'FileLeafRef\' Ascending=\'True\'></FieldRef></OrderBy></Query></View>';
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml(query);
        this.listCollection = list.getItems(camlQuery);
        context.load(this.listCollection, 'Include(' + config.fieldName + ',ID)');
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure));
    }
    catch (e) {
        SP.UI.Notify.addNotification(e, false);
    }
}
function onSuccess() {
    processResult(this.listCollection, config.fieldName);
}
function onFailure(sender, args) {
    SP.UI.Notify.addNotification(args.get_message(), false);
}

function processResult(oList,field) {
    try {
        var html = "<div id='pageNav'></div><input type='hidden' id='curPage' /><input type='hidden' id='pageItems' /><div id='content'> ";

        var listItemEnumerator = oList.getEnumerator();
        var x = 0;
        var maxChar = 30;
        while (listItemEnumerator.moveNext()) {
            x++;
            var oListItem = listItemEnumerator.get_current();
            id = oListItem.get_item('ID');
            title = oListItem.get_item(field);
            tLen = title.length;
            if (tLen > maxChar) {
                title = title.slice(0, -(tLen - maxChar));
                title += '...';
            }
            html += "<p class='quickSearchResultDivUnselected'><a href=\"javascript:EditItem2(event, '" + newUrl + "/DispForm.aspx?ID=" + id + "');\">" + title + "</a></p>";
        }

        $("#quickSearchResults").empty().append(html);
        $("#quickSearchResults").append("</div><div style='text-align:right;padding-left:2px;padding-top:5px;'>Total results: <b>" + x + "</b></div></div>")

        showResultsDiv();

        if (x != 0) {
            AddPager();
        } else {
            showResultsDiv("No matching results"); // display status
        }

    } catch (e) {
        SP.UI.Notify.addNotification(e, false);
    }

}

//******************************************************************************************
//PAGER
//******************************************************************************************
var totalPages;
function AddPager() {
 
    //how many items per page
    var pageItems = config.pageItems;
    //get no. of elements inside content div  
    var number_of_items = $('#content').children().size();
    //get the number of pages
    totalPages = Math.ceil(number_of_items / pageItems);

    //set the value of hidden fields  
    $('#curPage').val(0);
    $('#pageItems').val(pageItems);

    //create pager html
    var pagerHtml = '<center><div id="resultPager" style="display:none;"><a class="prevLink" href="javascript:navPrev();"><img alt="Previous" src="/_layouts/1033/images/prev.gif" border="0"/></a>';
    pagerHtml += '<a id="pageNum">1</a>' + '<a style="text-decoration:none;"> of ' + totalPages + '</a>';
    pagerHtml += '<a class="nextLink" href="javascript:navNext();"><img alt="Next" src="/_layouts/1033/images/next.gif" border="0"/></a><div></center>';
    $('#pageNav').html(pagerHtml);

    //hide all elements inside content div  
    $('#content').children().css('display', 'none');

    //show the first pageItems elements  
    $('#content').children().slice(0, pageItems).css('display', 'block');
    $('#resultPager').attr('style','display:block');
}

function navPrev() {
    currentPage = parseInt($('#curPage').val()) - 1;
    if (currentPage > -1)
        go_to_page(currentPage);
}

function navNext() {
    currentPage = parseInt($('#curPage').val()) + 1;
   if (currentPage < totalPages)
        go_to_page(currentPage);

}

function go_to_page(page_num) {
    //set current page on pager html
    $('#pageNum').text(page_num + 1);

    //get the number of items per page  
    var pageItems = parseInt($('#pageItems').val());

    //get the start the slice
    start_from = page_num * pageItems;

    //get the end the slice  
    end_on = start_from + pageItems;

    //hide all children elements of content div, get specific items and show them  
    $('#content').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');

    //update the current page input field  
    $('#curPage').val(page_num);
}  